# -*- coding: utf-8 -*- 
'''
Created on 2011-12-23

@author: TOM
'''
from compiler.ast import TryExcept
from django.db.models import Q
from django.http import HttpResponse
from django.utils.simplejson import dumps
from django.views.decorators.csrf import csrf_exempt
from website import utils, grids
from website.common import getCURoleId, getCompanyTuple, getEmployeId
from website.constant import SUPER_POWER
from website.employecontrol.models import Employe, Attendance, EmployeAttachment, \
    EmployeJZTeacherSalary, EmployeInsure, EmployePerformance
from website.resourcecontrol.models import Company, Department

#@csrf_exempt
#def employe_select(request):
#    data=[{'id':'1','name':'test1'},{'id':'2','name':'test2'}]
#    return HttpResponse(dumps(data))

#@csrf_exempt
#def employe_list(request):
#    results=Employe.objects.all();
#    return utils.JsonResponse(grids.ModelGrid(Employe).to_grid(results))



# 员工信息
@csrf_exempt
def employe_select(request):
    office_id=request.POST.get('office_id','')
    query=request.POST.get('query','')# 下拉框LIKE查询
    
    q=Q(state=1)
    q|=Q(state=2)
    q|=Q(state=4)
    q|=Q(state=5)
    
    if query !='' :
        q &=Q(name__contains=query)
    if office_id !='':
        q &=Q(office=office_id)
    
    results=Employe.objects.filter(q).values('id','name')#exclude(state=3)--->Employe.state != 3
    return utils.JsonResponse(dumps(list(results)))

# 员工信息
@csrf_exempt
def employe_select_all(request):
    query=request.POST.get('query','')# 下拉框LIKE查询
    
    q=Q(state=1)
    q|=Q(state=2)
    q|=Q(state=4)
    q|=Q(state=5)
    
    if query !='' :
        q &=Q(name__contains=query)

    
    results=Employe.objects.filter(q).values('id','name')#exclude(state=3)--->Employe.state != 3
    return utils.JsonResponse(dumps(list(results)))

# 员工信息-学管师
@csrf_exempt
def employe_select30(request):
    office_id='30'
    query=request.POST.get('query','')# 下拉框LIKE查询
    q=Q(state=1)
    q|=Q(state=2)
    q|=Q(state=4)
    q|=Q(state=5)
    
    if query !='' :
        q &=Q(name__contains=query)
    
    if office_id !='':
        q &=Q(office=office_id)
    
    results=Employe.objects.filter(q).values('id','name')#exclude(state=3)--->Employe.state != 3
    return utils.JsonResponse(dumps(list(results)))

# 员工信息-所有教师
@csrf_exempt
def employe_select29(request):
    office_id='29'
    query=request.POST.get('query','')# 下拉框LIKE查询
    q=Q(state=1)
    q|=Q(state=2)
    q|=Q(state=4)
    q|=Q(state=5)
    
    if query !='' :
        q &=Q(name__contains=query)
    
    if office_id !='':
        q &=Q(office=office_id)
    
    results=Employe.objects.filter(q).values('id','name')#exclude(state=3)--->Employe.state != 3
    return utils.JsonResponse(dumps(list(results)))

# 员工信息-兼职教师
@csrf_exempt
def employe_select29_5(request):
    office_id='29'
    query=request.POST.get('query','')# 下拉框LIKE查询
    q=Q(state=5)
    if query !='' :
        q &=Q(name__contains=query)
    
    if office_id !='':
        q &=Q(office=office_id)
        
    
    results=Employe.objects.filter(q).values('id','name')#exclude(state=3)--->Employe.state != 3
    return utils.JsonResponse(dumps(list(results)))


@csrf_exempt
def employe_tree(request):
    sort=request.POST.get('sort','0')
    nodes=[]
    if sort=='0': #校区
        companys=Company.objects.all()
        for comapny in companys:
            p_node={}
            #p_node['id']=comapny.id
            p_node['text']=comapny.cn_name
            p_node['leaf']=False
            p_node['checked']=False
            p_node['children']=[]
            employes=comapny.employe_school.exclude(state=3)
            for employe in employes:
                c_node={}
                c_node['id']=employe.id
                c_node['text']=employe.name
                c_node['leaf']=True
                c_node['checked']=False
                p_node['children'].append(c_node)
            nodes.append(p_node)
    elif sort=='1': #部门
        departments=Department.objects.all()
        for department in departments:
            p_node={}
            #p_node['id']=department.id
            p_node['text']=department.name
            p_node['leaf']=False
            p_node['checked']=False
            p_node['children']=[]
            employes=department.employe_department.exclude(state=3)
            for employe in employes:
                c_node={}
                c_node['id']=employe.id
                c_node['text']=employe.name
                c_node['leaf']=True
                c_node['checked']=False
                p_node['children'].append(c_node)
            nodes.append(p_node)     
    return utils.JsonResponse(dumps(nodes))


@csrf_exempt
def employe_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    name=request.POST.get('name','')
    state=request.POST.get('state','')
    course_desc=request.POST.get('course_desc','')
    company_id=request.POST.get('company_id','')
#    if getCURoleId(request) ==SUPER_POWER :
#        company_id=request.POST.get('company_id','')
#    else:
#        company_id = getCompanyTuple(request)[0]
    
    
    q=Q()
    if name <> '':
        q &=Q(name__contains=name)
    if state <> '':
        q &=Q(state=state)
    if company_id <>'':
        q &=Q(company=company_id)
    if course_desc <>'':
        q &=Q(course_desc__contains=course_desc)

    queryset=Employe.objects.filter(q)
    
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','name','gender','employed_data','positive_data',
        'identity_card','registered_residence','birthday','phone','email','qq','education','profession','graduate_school',
        'work_experience','state','leave_date','company_id','company__cn_name','department_id','department__name','office_id',
        'office__name','salary_grade','position_level','course_desc')),queryset.count()))

    


@csrf_exempt
def employe_save(request):
    employe_id=request.POST.get('id','')
    name=request.POST.get('name','')
    gender=request.POST.get('gender','')
    employed_data=request.POST.get('employed_data',None)
    positive_data=request.POST.get('positive_data',None)
    identity_card=request.POST.get('identity_card','')
    registered_residence=request.POST.get('registered_residence','')
    birthday=request.POST.get('birthday','')
    phone=request.POST.get('phone','')
    email=request.POST.get('email','')
    qq=request.POST.get('qq','')
    education=request.POST.get('education','')
    profession=request.POST.get('profession','')
    graduate_school=request.POST.get('graduate_school','')
    work_experience=request.POST.get('work_experience','')
    state=request.POST.get('state','2')
    leave_date=request.POST.get('leave_date',None)
    company_id=request.POST.get('company_id','')
    department_id=request.POST.get('department_id','')
    office_id=request.POST.get('office_id','')
    salary_grade=request.POST.get('salary_grade','')
    position_level=request.POST.get('position_level','')
    course_desc=request.POST.get('course_desc','')
    attachments=request.POST.get('attachments','')#附件
    
    if positive_data =='' : positive_data=None
    if leave_date =='' : leave_date=None
    try:
        if employe_id=='':
            Employe.objects.create(name=name,gender=gender,employed_data=employed_data,positive_data=positive_data,identity_card=identity_card,
                                   registered_residence=registered_residence,birthday=birthday,phone=phone,email=email,qq=qq,education=education,
                                   profession=profession,graduate_school=graduate_school,work_experience=work_experience,age=22,state=state,
                                   leave_date=leave_date,company_id=company_id,department_id=department_id,office_id=office_id,salary_grade=salary_grade,
                                   position_level=position_level,course_desc=course_desc)
        else:
            employe=Employe.objects.get(id=employe_id)
            employe.name=name
            employe.gender=gender
            employe.employed_data=employed_data
            employe.positive_data=positive_data
            employe.identity_card=identity_card
            employe.registered_residence=registered_residence
            employe.birthday=birthday
            employe.phone=phone
            employe.email=email
            employe.qq=qq
            employe.education=education
            employe.profession=profession
            employe.graduate_school=graduate_school
            employe.work_experience=work_experience
            employe.state=state
            employe.leave_date=leave_date
            employe.company_id=company_id
            employe.department_id=department_id
            employe.office_id=office_id
            employe.salary_grade=salary_grade
            employe.position_level=position_level
            employe.course_desc=course_desc
            employe.save()
            
            '''附件上传'''        
#        if attachments<>'':
#            _attachments=attachments.split(';')
#            for attachment in _attachments:
#                name,path=attachment.split(':')
#                EmployeAttachment.objects.create(name=name,path=path,letters=letters)            
            
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))


@csrf_exempt
def employe_del(request):
    try:
        ids=request.POST.get('ids','')

        if ids <> '':
            employe_ids=ids.rstrip(',').split(',')
            for employe_id in employe_ids:
                Employe.objects.get(id=employe_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))


@csrf_exempt
def employejzteachersalary_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    employe_id=request.POST.get('employe_id','')

    
    q=Q()
    if employe_id <> '':
        q &=Q(employe=employe_id)


    queryset=EmployeJZTeacherSalary.objects.filter(q)
    
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','employe_id','employe__name','x1','x2','x3','x4','x5','x6'
                                                                 ,'c1','c2','c3'
                                                                 ,'g1','g2','g3')),queryset.count()))

    


@csrf_exempt
def employejzteachersalary_save(request):
    e_id=request.POST.get('id','')
    employe_id=request.POST.get('employe_id','')
    x1=request.POST.get('x1','')
    x2=request.POST.get('x2','')
    x3=request.POST.get('x3','')
    x4=request.POST.get('x4','')
    x5=request.POST.get('x5','')
    x6=request.POST.get('x6','')
    c1=request.POST.get('c1','')
    c2=request.POST.get('c2','')
    c3=request.POST.get('c3','')
    g1=request.POST.get('g1','')
    g2=request.POST.get('g2','')
    g3=request.POST.get('g3','')
   
    try:
        if e_id=='':
            EmployeJZTeacherSalary.objects.create(employe_id=employe_id,x1=x1,x2=x2,x3=x3,x4=x4,x5=x5,x6=x6,
                                                  c1=c1,c2=c2,c3=c3,
                                                  g1=g1,g2=g2,g3=g3)
        else:
            employe=EmployeJZTeacherSalary.objects.get(id=e_id)
            employe.employe_id=employe_id
            employe.x1=x1
            employe.x2=x2
            employe.x3=x3
            employe.x4=x4
            employe.x5=x5
            employe.x6=x6
            employe.c1=c1
            employe.c2=c2
            employe.c3=c3
            employe.g1=g1
            employe.g2=g2
            employe.g3=g3
            employe.save()
            
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))


@csrf_exempt
def employejzteachersalary_del(request):
    try:
        ids=request.POST.get('ids','')

        if ids <> '':
            employe_ids=ids.rstrip(',').split(',')
            for employe_id in employe_ids:
                EmployeJZTeacherSalary.objects.get(id=employe_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))


#员工附件查找
@csrf_exempt
def employe_attachment_query(request):
    letters_id=request.POST.get('employeId','')
    results=EmployeAttachment.objects.filter(letters=letters_id).values('id','name','path')
    return utils.JsonResponse(dumps({'success':True,'data':list(results)}));



@csrf_exempt
def teacher_select(request):
    #TODO 过滤老师
    results=Employe.objects.all().values('id','name')
    return utils.JsonResponse(dumps(list(results)))



@csrf_exempt
def attendance_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    employe_id=request.POST.get('employe_id','')
    
    if getCURoleId(request) ==SUPER_POWER :
        company_id=request.POST.get('company_id','')
    else:
        company_id = getCompanyTuple(request)[0]
    
    
    q=Q()
    if employe_id <> '':
        q &=Q(employe__id=employe_id)
    if company_id<> '':
        q &=Q(employe__company=company_id)
        
    

    queryset=Attendance.objects.filter(q)
    
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','employe_id','employe__name','normal','no_card','dead',
                                                                 'fall_ill','no_work','donothing','arrive_late','work_overtime',
                                                                 'month_fee','attendance_deduction','other_deduction',
                                                                 'out_deduction','market_deduction','month')),queryset.count()))

@csrf_exempt
def attendance_save(request):
    attendance_id=request.POST.get('id','')
    employe_id=request.POST.get('employe_id','')
    normal=request.POST.get('normal','')
    no_card=request.POST.get('no_card','')
    dead=request.POST.get('dead','')
    fall_ill=request.POST.get('fall_ill','')
    no_work=request.POST.get('no_work','')
    donothing=request.POST.get('donothing','')
    arrive_late=request.POST.get('arrive_late','')
    work_overtime=request.POST.get('work_overtime','')
    month_fee=request.POST.get('month_fee','')
    attendance_deduction=request.POST.get('attendance_deduction','')
    other_deduction=request.POST.get('other_deduction','')
    out_deduction=request.POST.get('out_deduction','')
    market_deduction=request.POST.get('market_deduction','')
    month=request.POST.get('month','')
    
    try:
        if attendance_id=='':
            Attendance.objects.create(employe_id=employe_id,normal=normal,no_card=no_card,dead=dead,fall_ill=fall_ill,no_work=no_work,
                                      donothing=donothing,arrive_late=arrive_late,work_overtime=work_overtime,month_fee=month_fee,
                                      attendance_deduction=attendance_deduction,other_deduction=other_deduction,
                                      out_deduction=out_deduction,market_deduction=market_deduction,month=month)
        else:
            employe=Attendance.objects.get(id=attendance_id)
            employe.employe_id=employe_id
            employe.normal=normal
            employe.no_card=no_card
            employe.dead=dead
            employe.fall_ill=fall_ill
            employe.no_work=no_work
            employe.donothing=donothing
            employe.arrive_late=arrive_late
            employe.work_overtime=work_overtime
            employe.month_fee=month_fee
            employe.attendance_deduction=attendance_deduction
            employe.other_deduction=other_deduction
            employe.out_deduction=out_deduction
            employe.market_deduction=market_deduction
            employe.month=month
            employe.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))


@csrf_exempt
def attendance_del(request):
    try:
        ids=request.POST.get('ids','')

        if ids <> '':
            ids=ids.rstrip(',').split(',')
            for id1 in ids:
                Attendance.objects.get(id=id1).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))



# 员工保险
@csrf_exempt
def employeinsure_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    employe_id=request.POST.get('employe_id','')
    
    if getCURoleId(request) ==SUPER_POWER :
        company_id=request.POST.get('company_id','')
    else:
        company_id = getCompanyTuple(request)[0]
    
    
    q=Q()
    if employe_id <> '':
        q &=Q(employe__id=employe_id)
    if company_id<> '':
        q &=Q(employe__company=company_id)
        
    

    queryset=EmployeInsure.objects.filter(q)
    
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','employe_id','employe__name','month',
                                                                 'a','b','c','d','e','f')),queryset.count()))

@csrf_exempt
def employeinsure_save(request):
    attendance_id=request.POST.get('id','')
    employe_id=request.POST.get('employe_id','')
    month=request.POST.get('month','')
    a=request.POST.get('a','')
    b=request.POST.get('b','')
    c=request.POST.get('c','')
    d=request.POST.get('d','')
    e=request.POST.get('e','')
    f=request.POST.get('f','')
    
    try:
        if attendance_id=='':
            EmployeInsure.objects.create(employe_id=employe_id,month=month,a=a,b=b,c=c,d=d,e=e,f=f)
        else:
            employe=EmployeInsure.objects.get(id=attendance_id)
            employe.employe_id=employe_id
            employe.month=month
            employe.a=a
            employe.b=b
            employe.c=c
            employe.d=d
            employe.e=e
            employe.f=f
            employe.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))


@csrf_exempt
def employeinsure_del(request):
    try:
        ids=request.POST.get('ids','')

        if ids <> '':
            ids=ids.rstrip(',').split(',')
            for id1 in ids:
                EmployeInsure.objects.get(id=id1).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))







# 员工绩效
@csrf_exempt
def employeperformance_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    state=request.POST.get('state','')
    pref=request.POST.get('pref',False)
    start_day=request.POST.get('start_day','')
    
    #datetime.datetime.strptime(querytime,'%Y-%m-%d')
    # 这里只显示，当前员工下级职位 -同一分公司-下的所有员工
    #EmployePerformance.objects.filter(employe__company=7).filter(employe__office__in=(1,2,3))
    #curEmpOffice.office.child_office.all()
    
    
    
    '''
        获得当前用户校区
    '''
    companyId=getCompanyTuple(request)[0]
    '''
         获取当前用户的员工ID
    '''
    employeId=getEmployeId(request)
    '''
         获取当前用户的所有下属职务ID
    '''
    childOffice=Employe.objects.get(id=employeId).office.child_office.all()
    q=Q(employe__company=companyId )
    q&=Q(employe__office__in=childOffice)
    q|=Q(employe=employeId)
    if state <>'':
        q &=Q(state=state)
        
    
    
    
    
    
    '''
            预制人并且无下属职位的只能查自己的。
    '''
    if pref:
        if start_day <> '':
            queryset=EmployePerformance.objects.filter(employe=employeId,month__gte=start_day+'-01')
            return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
                list(queryset[int(start):int(start) + int(limit)].values('id','employe_id','employe__name','month','self_no',
                                                                         'department_no','department_man_id','department_man__name',
                                                                         'headquarter_no','headquarter_man_id','headquarter_man__name',
                                                                         'finally_no','finally_man_id','finally_man__name','remark','state','content')),queryset.count()))
        
        else:
            queryset=EmployePerformance.objects.filter(employe=employeId)
            return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
                list(queryset[int(start):int(start) + int(limit)].values('id','employe_id','employe__name','month','self_no',
                                                                         'department_no','department_man_id','department_man__name',
                                                                         'headquarter_no','headquarter_man_id','headquarter_man__name',
                                                                         'finally_no','finally_man_id','finally_man__name','remark','state','content')),queryset.count()))
        

    

    
    
    
    
    
    queryset=EmployePerformance.objects.filter(q)
    
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','employe_id','employe__name','month','self_no',
                                                                 'department_no','department_man_id','department_man__name',
                                                                 'headquarter_no','headquarter_man_id','headquarter_man__name',
                                                                 'finally_no','finally_man_id','finally_man__name','remark','state','content')),queryset.count()))



@csrf_exempt
def employeperformance_save(request):
    performance_id=request.POST.get('id','')
    employe_id=getEmployeId(request) ;
    month=request.POST.get('month','')
    self_no=request.POST.get('self_no','')
    department_no=request.POST.get('department_no','0')
    department_man_id=request.POST.get('employe_id','')
    finally_no=request.POST.get('finally_no','0')
    finally_man_id=request.POST.get('employe_id','')
    remark=request.POST.get('remark','')
    state=request.POST.get('state','0')
    content=request.POST.get('content','')
    try:
        if performance_id=='':
            EmployePerformance.objects.create(employe_id=employe_id,month=month,self_no=self_no,department_no=department_no,department_man_id=department_man_id,
                                              finally_no=finally_no,finally_man_id=finally_man_id,remark=remark,state=state,content=content)
        else:
            employe=EmployePerformance.objects.get(id=performance_id)
            employe.employe_id=employe_id
            employe.month=month
            employe.self_no=self_no
            employe.department_no=department_no
            employe.department_man_id=department_man_id
            employe.finally_no=finally_no
            employe.finally_man_id=finally_man_id
            employe.remark=remark
            employe.state=state
            employe.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))

@csrf_exempt
def employeperformance_update_state1(request):
    # 提交审核
    performance_id=request.POST.get('id','')
    state=request.POST.get('state','')
    
    try:
            employe=EmployePerformance.objects.get(id=performance_id)
            employe.state=state
            employe.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))

@csrf_exempt
def employeperformance_update_dep_no(request):
    # 部门修改分数
    performance_id=request.POST.get('id','')
    department_no=request.POST.get('department_no','')
    content=request.POST.get('content','')
    try:
            employe=EmployePerformance.objects.get(id=performance_id)
            employe.department_no=department_no
            employe.department_man_id=getEmployeId(request)
            employe.content=content
            employe.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))

@csrf_exempt
def employeperformance_update_finally_no(request):
    # 最终修改分数
    performance_id=request.POST.get('id','')
    finally_no=request.POST.get('finally_no','')
    content=request.POST.get('content','')
    try:
            employe=EmployePerformance.objects.get(id=performance_id)
            employe.finally_no=finally_no
            employe.finally_man_id=getEmployeId(request)
            employe.content=content
            employe.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))

@csrf_exempt
def employeperformance_del(request):
    try:
        ids=request.POST.get('ids','')

        if ids <> '':
            ids=ids.rstrip(',').split(',')
            for id1 in ids:
                EmployePerformance.objects.get(id=id1).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))







